<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-select v-model="query.onlineStatus" placeholder="在线状态" clearable>
          <el-option
              v-for="item in selectsData.status_select"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-input v-model="query.laneName" placeholder="车道名称" clearable/>
        <el-button type="primary" :icon="Search" @click="handleSearch">
        </el-button>
        <el-button @click="handleClear">重置</el-button>
      </div>
      <div class="handle-box">
        <el-button type="primary" :icon="Plus" @click="handleEdit()">添加</el-button>
        <el-button :disabled="!multipleSelection.length" @click="handleChangeItem(multipleSelection,'batchDel')">批量删除
        </el-button>
      </div>
      <el-table
          :data="tableData"
          max-height="calc(100vh - 250px)"
          border
          class="table"
          @selection-change="handleSelectionChange"
          header-cell-class-name="table-header">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="parkingName" label="车场名称" align="center" min-width="120">
          <template #default="scope">
            <span>{{ scope.row?.cityName + ' - ' + scope.row.parkingName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="parkingId" label="车场ID" align="center"></el-table-column>
        <el-table-column prop="laneName" label="车道名称" align="center"></el-table-column>
        <el-table-column prop="onlineStatus" label="在线状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.onlineStatus == 1 ? 'success': 'info'">{{
                scope.row.onlineStatus == 1 ? '在线' : '离线'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="scope">
            <div class="btns">
              <el-button-group style="margin-right: 12px">
<!--                :disabled="scope.row.onlineStatus !== 1"-->
                <el-button
                    type="success" size="small"
                    :disabled="true"
                    :title="scope.row.onlineStatus !== 1 ? '离线状态暂不支持开关闸':'点击开闸'"
                    @click="handleChangeItem({...scope.row,isOpen: true}, 'openEdit')">开闸
                </el-button>
<!--                :disabled="scope.row.onlineStatus !== 1"-->
                <el-button type="info" size="small"
                           :disabled="true"
                           :title="scope.row.onlineStatus !== 1 ? '离线状态暂不支持开关闸':'点击关闸'"
                           @click="handleChangeItem({...scope.row,isOpen: false}, 'closeEdit')">关闸
                </el-button>
              </el-button-group>
              <el-button type="primary" size="small"
                         @click="handleEdit(scope.row)"
              >编辑
              </el-button>
              <el-button type="danger" size="small"
                         @click="handleChangeItem(scope.row, 'del')">删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
            hide-on-single-page
            v-model:current-page="query.page"
            v-model:page-size="query.pageSize"
            background
            :page-sizes="[10, 20, 30, 40, 50, 100, 200]"
            layout="prev, pager, next, jumper, total, sizes"
            :total="pageTotal"
            @current-change="handlePageChange"
            @size-change="handleLimitChange"
        ></el-pagination>
      </div>
    </div>
    <!--    添加/编辑弹框-->
    <el-dialog v-model="dialogVisible" destroy-on-close :title="addVisible ? '添加车道' : '编辑车道'"
               width="50%"
               draggable>
      <el-form
          ref="ruleFormRef"
          :rules="rules"
          :model="editform"
          label-width="auto"
      >
        <el-form-item label="车场名称" prop="parkingName">
          <el-select
              v-model="editform.parkingName"
              placeholder="请选择车场"
              filterable
              @change="(val:any)=>handleSelectChange('cityId',val)"
          >
            <el-option
                v-for="item in selectsData.parking_select"
                :key="item.parkingName"
                :label="item.cityName + ' - ' + item.parkingName"
                :value="item.parkingName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车道名称" prop="laneName">
          <el-input v-model="editform.laneName"></el-input>
        </el-form-item>
        <el-form-item label="相机序列号" prop="serialNumber">
          <el-input v-model="editform.serialNumber"></el-input>
        </el-form-item>
        <el-form-item label="辅助相机序列号" prop="auxiliarySerialNumber">
          <el-input v-model="editform.auxiliarySerialNumber"></el-input>
        </el-form-item>
        <el-form-item label="相机型号" prop="photoName">
          <el-radio-group v-model="editform.photoName">
            <el-radio v-for="item in selectsData.camera_select" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出入口类型" prop="inOrOut">
          <el-radio-group v-model="editform.inOrOut">
            <el-radio v-for="item in selectsData.entrance_select" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="saveItem(ruleFormRef)">立即提交</el-button>
        <el-button @click="handleEditClear">重置</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="parkingLine">
import {ref, reactive, computed, getCurrentInstance, ComponentInternalInstance} from 'vue';
import {ElMessage, ElMessageBox, FormInstance, FormRules} from 'element-plus';
import {Delete, Edit, CopyDocument, Search, Plus} from '@element-plus/icons-vue';
import {ParkingMgt} from "@/api";
import {useRoute, useRouter} from "vue-router"
import useClipboard from 'vue-clipboard3';
import moment from 'moment';

const $moment = moment
defineExpose({
  $moment
})

const {toClipboard} = useClipboard();
const copy = async (text) => {
  try {
    await toClipboard(text);  //实现复制
    ElMessage.success('复制成功')
  } catch (e) {
    console.error(e);
  }
};

const handleSelectChange = (key: string, value: any) => {
  if (key === 'cityId') {
    editform.cityId = (selectsData.value.parking_select || []).find((item: any) => item.parkingName == value)?.cityId;
  }
}

interface TableItem {
  id?: string;
}

const query = reactive({
  onlineStatus: undefined,
  parkingName: undefined,
  laneName: undefined,
  page: 1,
  pageSize: 10
});

const reset = () => {
  query.onlineStatus = undefined;
  query.parkingName = undefined;
  query.laneName = undefined;
  query.page = 1;
  query.pageSize = 10;
};

const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
// 获取表格数据
const getData = () => {
  ParkingMgt.getParkingLaneList(query).then((res: any) => {
    tableData.value = res.data.data.list;
    pageTotal.value = res.data.data?.total || res.data.data?.list?.length || 10;
  });
};
const route = useRoute();
if (route.query) {
  for (let i in route.query) {
    if (query.hasOwnProperty(i) && route.query[i] !== undefined) {
      query[i] = route.query[i];
    }
  }
}
getData();

const selectsData: any = ref({
  camera_select: [
    {label: "wwl-cp01", value: 'wwl-cp01'},
    {label: "wwl-cp02", value: 'wwl-cp02'},
    {label: "wwl-cp03", value: 'wwl-cp03'},
  ],
  entrance_select: [
    {label: "入口", value: '0'},
    {label: "出口", value: '1'}
  ],
  status_select: [
    {label: "在线", value: '1'},
    {label: "离线", value: '0'}
  ],
});

const getSelectData = () => {
  ParkingMgt.getParkingItemList({page: -1}).then((res: any) => {
    selectsData.value = {
      ...selectsData.value,
      parking_select: res.data.data?.list || []
    }
  });
};
getSelectData();

const multipleSelection = ref<TableItem[]>([])
const handleSelectionChange = (val: TableItem[]) => {
  multipleSelection.value = val
}

const handleBatch = (key: string, contTxt: string, params?: any) => {

};


const handleSearch = () => {
  getData();
};

const handleClear = () => {
  reset();
  ElMessage.success("重置成功！");
  getData();
};

const handlePageChange = (val: number) => {
  query.page = val;
  getData();
};

const handleLimitChange = (val: number) => {
  query.page = 1;
  query.pageSize = val;
  getData();
};
const editVisible = ref(false);
const addVisible = ref(false);
let editform = reactive<any>(({
  cityId: undefined,
  parkingName: undefined,
  laneName: undefined,
  serialNumber: undefined,
  auxiliarySerialNumber: undefined,
  photoName: undefined,
  inOrOut: undefined,
}));

// const
const handleEdit = (row?: any) => {
  handleEditClear(true);
  if (row) {
    editVisible.value = true;
    for (const key in row) {
      if (row[key] !== undefined && editform.hasOwnProperty(key)) {
        editform[key] = row[key];
      }
    }
    editform.id = row.id;
  } else {
    addVisible.value = true;
  }
};

const handleEditClear = (clearAll?: boolean) => {
  for (const key in editform) {
    if (!clearAll && key === 'id') continue;
    if (key === 'inOrOut') {
      editform[key] = '0';
    } else if (key === 'photoName') {
      editform[key] = 'wwl-cp01';
    } else {
      editform[key] = '';
    }
  }
};

const dialogVisible = computed({
  get: () => !!(addVisible.value || editVisible.value),
  set: (val) => {
    addVisible.value = val;
    editVisible.value = val;
  }
});

const siteSelection = computed({
  get: () => {
    if (addVisible.value) {
      return editform.web_ids || []
    } else {
      return {key: editform.web_id}
    }
  },
  set: (val: any) => {
    editform.web_name = '';
    addVisible.value ? (editform.web_ids = val) : (editform.web_id = val.key);
  }
})

const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  laneName: [{required: true, message: '请输入车道名称', trigger: 'blur'}],
  parkingName: [{required: true, message: '请选择车场名称', trigger: 'change'}],
  photoName: [{required: true, message: '请选择相机型号', trigger: 'change'}],
  inOrOut: [{required: true, message: '请选择出入口类型', trigger: 'change'}],
  // project_name: [
  //   {required: true, message: '请输入项目名称', trigger: 'blur'},
  //   {min: 1, max: 15, message: '长度不能超过15', trigger: 'blur'},
  // ],
  // category_name: [
  //   {required: true, message: '请输入分类名称', trigger: 'blur'},
  //   {min: 1, max: 6, message: '长度不能超过6', trigger: 'blur'},
  // ]
})

const saveItem = async (formEl?: FormInstance | undefined) => {
  const newFormEl = formEl?.[0] ? formEl[0] : formEl;
  if (newFormEl) {
    const valid = await newFormEl.validate((valid, fields) => !!valid);
    if (!valid) return;
  }

  let apiFun, params = {}
  if (addVisible.value) {
    apiFun = ParkingMgt.addParkingLine;
    params = {parkingLanes: [{...editform}]};
  } else if (editVisible.value) {
    apiFun = ParkingMgt.updateParkingLine;
    params = {...editform}
  }
  if (!apiFun) return;
  apiFun({...params}).then((res: any) => {
    if (res.data.status === 1) {
      addVisible.value && (addVisible.value = false);
      editVisible.value && (editVisible.value = false);
      ElMessage.success(res.data.msg);
      getData();
    } else {
      ElMessage.error(res.data.msg);
    }
  })
}

const handleChangeItem = (data: any, type: string) => {
  let contTxt = '', themeTxt = '', apiFun: any = '', apiParams: any = {};
  if (type === 'del') {
    contTxt = '删除车道'
    themeTxt = ' ' + data.laneName + ' ';
    apiFun = ParkingMgt.deleteParkingLine;
    apiParams = {ids: [data.id]}
  } else if (type === 'batchDel') {
    contTxt = '删除选中的车道'
    apiFun = ParkingMgt.deleteParkingLine;
    apiParams = {ids: data.map(item => item.id)}
  } else if (type === 'openEdit' || type === 'closeEdit') {
    contTxt = ((type === 'openEdit') ? '开闸' : '关闸');
    apiFun = ParkingMgt.updateParkingLine;
    apiParams = {...data}
  }
  if (!apiFun) return;
  ElMessageBox.confirm(`确定要${contTxt + themeTxt}吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    apiFun(apiParams).then((res: any) => {
      if (res.data.status === 1) {
        let msg = res.data.msg;
        if (type === 'openEdit') {
          msg = '开闸命令已发送'
        } else if (type === 'closeEdit') {
          msg = '关闸命令已发送'
        }
        ElMessage.success(msg);
        getData();
      } else {
        ElMessage.error(res.data.msg);
      }
    })
  })
      .catch(() => {
      });
};

</script>

<style lang="less" scoped>
.handle-box {
  display: flex;
  flex-wrap: wrap;

  :deep(.el-date-editor),
  .el-select,
  .el-input {
    margin-right: 10px;
    min-width: 350px;
    flex: 1;
  }

  :deep(.el-date-editor),
  .el-select,
  .el-input,
  .el-button {
    margin-bottom: 10px;
  }

  :deep(.responseTime) {
    margin-right: 10px;
    //min-width: 350px;
    flex: 1;
    display: flex;
    align-items: center;

    .startTime,
    .endTime {
      flex: 1;
      margin-right: 0px;
    }

    .startTime {
      .el-input__wrapper {
        border-radius: 0;
      }
    }

    .endTime {
      .el-input-group__prepend {
        border-radius: 0;
        box-shadow: 0px 0 0 0 var(--el-input-border-color) inset, 0 1px 0 0 var(--el-input-border-color) inset,0 -1px 0 0 var(--el-input-border-color) inset;
      }
    }

  }
}

.el-table {
  .resultItem {
    color: inherit;
    cursor: pointer;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    &:hover {
      color: #20a0ff;
    }
  }

  :deep(.el-switch__core) {
    width: 55px;
  }

  .btns {
    display: flex;
    justify-content: center;
  }
}

.el-dialog {
  .el-select {
    width: 100%;
  }

  .tip {
    color: red;
  }
}
</style>
